package com.ruoyi.web.controller.mxerp;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.system.service.CommonUtilUrlService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;

@RestController
@RequestMapping("/mxerp/img")
public class MxImageComController extends BaseController {
    @Autowired
    private CommonUtilUrlService commonUtilUrlService;

    @Value("${img.key}")
    private String key;

    @Value("${img.imgurl}")
    private String imgurl;

    @PostMapping("/mx_image")
    public AjaxResult saveJpg(@RequestParam MultipartFile file) throws Exception {
        if (!file.isEmpty()){
            byte[] fileContent = IOUtils.toByteArray(file.getInputStream());
            String baseImg = Base64.getEncoder().encodeToString(fileContent);

            JSONObject json = new JSONObject();
            json.put("key",key);
            json.put("imgStr",baseImg);
            String baseUrl = commonUtilUrlService.post(imgurl,json.toString());

            System.out.println(baseUrl);
//            LoginUser loginUser = getLoginUser();
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", baseUrl);
            return ajax;
        }
        return error("上传图片异常，请联系管理员");
    }
}
